<template>
	<view class="container">
		<!-- <CustomNavbar :title="id ? '编辑地址' : '添加地址'"></CustomNavbar> -->
		<u-form labelWidth="174rpx" :labelStyle="{ fontSize: '26rpx',fontWeight: 'bold' }">
			<!-- 姓名 -->
			<u-form-item label="姓名" borderBottom>
				<u-input v-model="formData.delivery_name" placeholder="请输入姓名" border="none"
					inputAlign="right"></u-input>
			</u-form-item>

			<!-- 电话 -->
			<u-form-item label="电话" borderBottom>
				<u-input v-model="formData.delivery_phone" placeholder="请输入手机号码" border="none" inputAlign="right"
					type="number"></u-input>
			</u-form-item>

			<!-- 地区选择 -->
			<u-form-item label="地区" borderBottom @click="openPicker">
				<view v-if="regionText" style="font-size: 32rpx">{{ regionText }}</view>
				<view v-else style="color:#ccc;font-size: 32rpx">请选择省/市/区/街道</view>
				<image class="address" src="/addressPages/static/address_right.png" mode="widthFix"></image>
				<u-picker :show="showRegionPicker" :columns="regionColumns" keyName="label" @change="onPickerChange"
					@confirm="confirmRegion" @cancel="showRegionPicker = false" :immediateChange="true"
					confirmColor="#FD3832"></u-picker>

			</u-form-item>

			<!-- 详细地址 -->
			<u-form-item label="详细地址" borderBottom>
				<u-input v-model="formData.delivery_addr" placeholder="请输入详细地址，具体到门牌号" border="none"
					inputAlign="right"></u-input>
			</u-form-item>

			<!-- 邮编 -->
			<u-form-item label="邮箱编码" borderBottom>
				<u-input v-model="formData.postcode" placeholder="请输入邮编" border="none" type="number"
					inputAlign="right"></u-input>
			</u-form-item>

			<!-- 默认地址 -->
			<u-form-item label="设为默认地址">
				<view class="switch" @click="formData.is_default=!formData.is_default">
					<image
						:src="formData.is_default?'/addressPages/static/switch_active.png':'/addressPages/static/switch.png'"
						mode="widthFix"></image>
				</view>
			</u-form-item>

		</u-form>
		<AddBtn :title="id ? '编辑地址':'添加地址'" @addAddress="addAddress" />
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted,
		nextTick
	} from 'vue';
	import CustomNavbar from '@/components/CustomNavbar.vue';
	import AddBtn from '/addressPages/components/AddBtn.vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import rawData from '@/static/addressData/pcas-code.json';
	const id = ref(null);
	onLoad((options) => {
		id.value = options.id;
		if (id.value) {
			getData();
		}
		// 动态修改导航栏标题
		uni.setNavigationBarTitle({
			title: id ? '编辑地址' : '添加地址'
		});
	});

	// 验证手机号格式的函数
	const validatePhone = (phone) => {
		const reg = /^1(3[0-9]|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/;
		return reg.test(phone);
	}

	// 表单数据
	const formData = ref({
		delivery_name: '',
		delivery_phone: '',
		prov: '',
		city: '',
		area: '',
		street: '',
		delivery_addr: '',
		postcode: '',
		is_default: 0
	});

	const getData = () => {
		uni.$api.user.addressDetail({
			id: id.value
		}).then(res => {
			if (res.code == 200) {
				res.data.is_default = parseInt(res.data.is_default);
				formData.value = res.data;
			}
		});
	}

	// 地址显示
	const regionText = computed(() => {
		return [formData.value.prov, formData.value.city, formData.value.area, formData.value.street]
			.filter(Boolean)
			.join('/');
	});

	// 验证逻辑
	const checkPhone = () => {
		if (!validatePhone(formData.value.delivery_phone)) {
			uni.showToast({
				title: '请输入正确的手机号码',
				icon: 'none'
			});
			return false;
		}
		return true;
	}

	const checkName = () => {
		if (!formData.value.delivery_name) {
			uni.showToast({
				title: '请输入姓名',
				icon: 'none'
			});
			return false;
		}
		return true;
	}

	const checkAddress = () => {
		if (!formData.value.prov || !formData.value.delivery_addr) {
			uni.showToast({
				title: '请选择收货地址',
				icon: 'none'
			});
			return false;
		}
		return true;
	}

	const checkAll = () => {
		return checkName() && checkPhone() && checkAddress();
	}

	// 地区选择相关
	const showRegionPicker = ref(false);
	// 处理原始数据（深拷贝解除冻结）
	const formatRegionData = (data) => {
		return data.map(item => ({
			label: item.name,
			value: item.code,
			children: item.children ? formatRegionData(item.children) : []
		}));
	}



	const regionTree = ref([]); // 深拷贝原始数据
	const regionColumns = ref([
		[],
		[],
		[],
		[]
	]);
	const selectedIndexes = ref([0, 0, 0, 0]); // 维护选中路径
	// 1. 修改数据初始化逻辑
	onMounted(async () => {
		try {
			const clonedData = JSON.parse(JSON.stringify(rawData));
			regionTree.value = formatRegionData(clonedData);

			// 延迟确保数据加载完成
			await nextTick();

			// 安全初始化默认选择
			if (regionTree.value.length > 0) {
				initDefaultSelection();
			} else {
				selectedIndexes.value = [0, 0, 0, 0]; // 安全默认值
			}
		} catch (e) {
			console.error('数据初始化失败:', e);
		}
	});
	// 2. 强化默认选择逻辑
	const initDefaultSelection = () => {
		const indexes = [];
		let current = regionTree.value;

		for (let i = 0; i < 4; i++) {
			if (current?.length > 0) {
				indexes[i] = 0;
				current = current[0]?.children; // 安全访问
			} else {
				indexes[i] = 0; // 安全默认值
				current = [];
			}
		}

		selectedIndexes.value = indexes;
		updateColumns(indexes); // 初始化时传递有效参数
	};

	// 修改动态加载逻辑（核心修复）
	const updateColumns = (indexes) => {
		const newColumns = [];
		let currentLevel = regionTree.value;

		for (let level = 0; level < 4; level++) {
			// 1. 安全获取当前层级数据
			const currentData = Array.isArray(currentLevel) ? currentLevel : [];
			newColumns[level] = [...currentData];

			// 2. 根据选中索引加载下一级数据（关键修改点）
			if (indexes[level] >= 0 && currentData[indexes[level]]?.children) {
				currentLevel = currentData[indexes[level]].children; // ✅ 正确获取子级
			} else {
				currentLevel = []; // 清空后续数据
			}
		}

		// 3. 强制更新组件
		regionColumns.value = newColumns.map(col => [...col]);
	};


	// 打开地址选择器
	const openPicker = () => {
		if (regionColumns.value[0]?.length === 0) {
			initDefaultSelection();
		}
		showRegionPicker.value = true;
		updateColumns(selectedIndexes.value); // 显式传递当前选中索引
	};
	// 修改后的选择事件处理
	const onPickerChange = (e) => {
		// 安全获取选中索引（兼容不同版本参数）
		const rawIndexes = e.indexs ||
			(e.value?.map((_, i) => e.index?.[i]) || []);
		// 补全并校验索引值
		const safeIndexes = [];
		for (let i = 0; i < 4; i++) {
			const idx = typeof rawIndexes[i] === 'number' ?
				Math.max(0, Math.min(rawIndexes[i], regionColumns.value[i]?.length - 1 || 0)) :
				0;
			safeIndexes.push(idx);
		}

		selectedIndexes.value = safeIndexes;
		updateColumns(safeIndexes);
	};

	const confirmRegion = (e) => {
		const values = e.value;
		formData.value.prov = values[0]?.label || '';
		formData.value.city = values[1]?.label || '';
		formData.value.area = values[2]?.label || '';
		formData.value.street = values[3]?.label || '';
		showRegionPicker.value = false;
	};

	// 添加/编辑地址
	const addAddress = () => {
		if (!checkAll()) return;

		const request = id.value ?
			uni.$api.user.editaddress({
				...formData.value,
				id: id.value
			}) :
			uni.$api.user.addAddress(formData.value);

		request.then(res => {
			if (res.code == 200) {
				uni.showToast({
					title: res.msg
				});
				if (!id.value) uni.setStorageSync('address', JSON.stringify(formData.value));
				setTimeout(() => uni.navigateBack(), 1000);
			}
		});
	}
</script>

<style lang="scss" scoped>
	.container {
		background: url('/static/index_slices/index_bg.png') no-repeat;
		background-size: 100% auto;
		padding-top: 28rpx;
	}

	.u-form {
		background-color: #fff;
		border-radius: 26rpx;
		padding: 49rpx 44rpx 71rpx;
		margin: 20rpx;
	}

	::v-deep .u-form-item .u-form-item__body__right__content__slot[data-v-42bac3de] {
		justify-content: flex-end;
	}

	.u-form-item {
		margin-top: 20rpx;
		height: 110rpx;
		border-bottom: 1rpx solid #EEF3F6;
		color: #101624;
		font-size: 26rpx;

		.address {
			width: 10rpx;
			margin-left: 40rpx;
		}

		.switch {
			text-align: right;

			image {
				width: 84rpx;
			}
		}
	}
</style>